/**
 * Created by Administrator on 2018/3/28.
 */
require('../../../less/back/runMontior/runMontior.less');
import $ from 'jQuery';
(function () {
    let $tree = null;
    let map = null;
    let currentNodes=new Array();
    var operateParam={}; //操作参数，区分新增和更新
    var drawingManager =null;
    var currentMarker =null;
    var addGroupName = null; //临时组名称
    let $vue = new Vue({
        el: '.runMontior-main-hook',
        data: {
            lightStatus: [{id: 1, name: '开灯'}, {id: 2, name: '关灯'},{id: 3, name: '不全开'},{id: 4, name: '故障'},{id: 5, name: '离线'}],
            faultType:[{id: 1, name: '故障A'}, {id: 2, name: '故障B'},{id: 3, name: '故障C'}],
            message  : [{id: 0, name: '通讯正常'}, {id: 1, name: '通讯失败'}],
            idNum:[{id:1,name:'IMSI号'},{id:2,name:'单灯编号'},{id:3,name:'灯杆编号'},{id:4,name:'终端ID'}],
            cityName:'',
            clickAble:false,
            lambListAll:[
                { lightStr: '20'},
                { lightStr: '30'},
                { lightStr: '40'}
            ],
            info:{
                lightName:'灯盏A',
                onenetCode:'123456788',
                conCategory:'1',
                status:'2',
                proCode:'333',
                proName:'aaaa',
                cUser:'abde',
                imei:"111111111111",
                imsi:"111111111111",
            },
            temList:[
                {
                    lambName:'灯盏A',
                    lambNo:"1122"
                },
                {
                    lambName:'灯盏B',
                    lambNo:"11242"
                }
            ],
            itemStateList:[
                {
                    id:'1',eleV:'12',eleA:'23',eleW:'21',eleL:'34'
                },
                {
                    id:'2',eleV:'22',eleA:'21',eleW:'22',eleL:'14'
                }
            ]

        },
        methods: {
            searchForm:function(){   //查询ztree
                var $form = $(".search-hook");
                var formParams = $form.serializeJson();
                search(formParams);
            },
            searchCity:function(){
                var local = new BMap.LocalSearch(map, {
                    renderOptions:{map: map}
                });
                let  cityName = $vue.$data.cityName;
              /*  var re = /^\d{1,12}(\.\d{1,6})?$/;
                if(!re.test(cityName)==true){
                    $vue.$data.cityName='';
                }*/
                local.search(cityName);
            },
            delItem:function (index) {
                layer.confirm('请问是否确认删除该单灯？', {
                    btn: ['是','否']
                }, function(){
                    layer.closeAll();
                    $vue.$data.temList.splice(index, 1)
                }, function(){

                });

            },
            closeDetail:function(){
                $('.detail_tem').hide();
            },
            closeDialog:function(){  //关闭弹窗
                   $('#map_tap').hide();
                   currentMarker =null;
            },
            temGroup:function () {   //新建临时组，画轨迹

                layer.open({
                    type: 1,
                    title: '新增临时组',
                    shadeClose: true,
                    resize: false,
                    shade: 0.4,
                    area: ['400px', '200px'],
                    skin: 'layui-layer-rim',
                    btn: ['确定','取消'],
                    content: $('#modal-dialog'),
                    yes:function(){    //确定执行

                        if($('#range_title').val() ==''){
                            IOT.tips('请输入临时组名称！', 'error', 1000, null);
                            return;
                        }
                        if($('#range_title').val().trim()){
                            addGroupName =$('#range_title').val();
                            layer.closeAll();//会清空表单
                            drawingManager.open();
                        }else{
                            IOT.tips('请输入临时组名称！', 'error', 1000, null);
                            return;
                        }
                    },
                    no:function(){
                        $('#range_title').val('');
                    },
                    success: function () {   //弹窗开始前执行
                        $('#range_title').val('');
                        operateParam={};
                        /*clearMap();*/
                    },end:function(){      //弹窗结束前执行
                        $('#range_title').val('');
                    }
                });

            },
            timelyControl:function () {
                $vue.$data.lambListAll=[
                    { lightStr: '50'},
                    { lightStr: '70'},
                    { lightStr: '20'}
                ];
                this.$nextTick(() => {
                    new scale('.User_grade');
                });
            },
            surOperation:function () {   //实时控制确认按钮

                let lightLevel =$vue.$data.lambListAll;
                console.log($vue.$data.lambListAll);
                IOT.getServerData(URI.RUN_MONTIOR.CONTROL_LIGHT, lightLevel, (ret) => {
                    IOT.showOverlay('执行操作中，请稍等...');
                    if (ret.code === 200) {
                        IOT.hideOverlay();

                    } else {
                        IOT.tips(ret.msg, 'error');
                    }
                });
            },
            lambList:function () {    //单灯信息
                console.log(currentMarker);
               /* var lambId ='';
                IOT.getServerData(URI.RUN_MONTIOR.LIGHT_LIST, lambId, (ret) => {
                    IOT.showOverlay('数据获取中，请稍等...');
                    if (ret.code === 200) {
                        IOT.hideOverlay();

                    } else {
                        IOT.tips(ret.msg, 'error');
                    }
                });*/
            },
            showLog:function(){  //展示终端日志
                initLog();
            }
        },
        mounted: function () {
            this.$nextTick(() => {
                initMap();
                search("");
                //添加鼠标绘制工具监听事件，用于获取绘制结果
                /*   drawingManager.addEventListener('rectanglecomplete', overlaycomplete);*/
                drawingManager.addEventListener('rectanglecomplete', polygoncomplete);
            });
        }

    });
    var search = function(formParams){
        var setting = {
            data: {
                simpleData: {
                    enable: true,
                    idKey: 'id',
                    pIdKey: 'pid',
                    rootPId: 0
                }
            },
            view:{
                selectedMulti: false,//不允许同时选中多个节点
                showIcon :false,
                showLine:false,
            },
            callback: {
                onClick:function onCheckTreeNode(event, treeId, treeNode){
                    currentNodes.length=0;
                    $vue.$data.clickAble = true;
                    setCurrentNodes(treeNode);
                    drawOverlays();//展示网点标记
                    if (treeNode.lev == 0 || treeNode.level == 0){
                        addGroup();
                    }
                }
            }
        };
        IOT.getServerData(URI.RUN_MONTIOR.TREE, formParams, (ret) => {
            IOT.showOverlay('获取数据中，请稍等...');
            if (ret.code === 200) {
                IOT.hideOverlay();
                currentNodes.length=0;
                ret.data =[{"id":1,"pid":-1,"name":"项目A","level":1,"status":null,"lng":null,"lat":null,"address":'重庆市'},
                    {"id":2,"pid":1,"name":"分组A","level":2,"status":null,"lng":null,"lat":null,"address":'重庆市'},
                    {"id":3,"pid":2,"name":"单灯a","level":3,"status":'2',"lng":'106.506573',"lat":'29.62',"address":'重庆市'},
                    {"id":4,"pid":2,"name":"单灯b","level":3,"status":'3',"lng":'106.596573',"lat":'29.52',"address":'重庆市'},
                    {"id":4,"pid":2,"name":"单灯c","level":3,"status":'1',"lng":'105.896573',"lat":'30.02',"address":'重庆市'},
                    {"id":12,"pid":1,"name":"分组B","level":2,"status":null,"lng":null,"lat":null,"address":'重庆市'},
                    {"id":3,"pid":12,"name":"单灯aA","level":3,"status":'3',"lng":'106.583',"lat":'29.92',"address":'重庆市'},
                    {"id":4,"pid":12,"name":"单灯bB","level":3,"status":'2',"lng":'106.983',"lat":'29.92',"address":'重庆市'},
                    {"id":4,"pid":12,"name":"单灯cC","level":3,"status":'2',"lng":'107.083',"lat":'29.12',"address":'重庆市'},
                    {"id":11,"pid":-1,"name":"项目B","level":1,"status":null,"lng":null,"lat":null,"address":'北京市'},
                    {"id":111,"pid":11,"name":"分组BB","level":2,"status":null,"lng":'115.860125',"lat":'39.42562',"address":'北京市'},
                    {"id":112,"pid":111,"name":"单灯B","level":3,"status":'4',"lng":'116.360125',"lat":'39.92562',"address":'北京市'},
                    {"id":113,"pid":111,"name":"单灯BB","level":3,"status":'5',"lng":'116.960125',"lat":'39.02562',"address":'北京市'}
                ];
                let treeList = ret.data;
                $tree = $.fn.zTree.init($('#runMontior_tree'), setting, treeList);
                $tree.expandAll(true);
                setCurrentNodes($tree.getNodes()[0]);
                drawOverlays();//展示网点标记
            } else {
                IOT.tips(ret.msg, 'error');
            }
        });
    };
    //初始化地图
    var initMap = function(){
        map = new BMap.Map("runMontior_map",{enableMapClick: false});    // 创建Map实例
        var point = new BMap.Point(	103.73, 36.03);  // 创建点坐标
        map.centerAndZoom(point,5); //初始化地图,设置中心点坐标和地图级别
        map.enableScrollWheelZoom(true);  //开启鼠标滚轮缩放*/
        map.addControl(new BMap.NavigationControl());
        map.addControl(new BMap.ScaleControl());
        map.addControl(new BMap.OverviewMapControl());
        //实例化鼠标绘制工具
        drawingManager = new BMapLib.DrawingManager(map, {
            isOpen: false, //是否开启绘制模式
            enableDrawingTool: false, //是否显示工具栏
            drawingMode:BMAP_DRAWING_RECTANGLE,//绘制模式  矩形
            drawingToolOptions: {
                anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
                offset: new BMap.Size(5, 5), //偏离值
                drawingModes:[
                    BMAP_DRAWING_RECTANGLE
                ]
            },
            rectangleOptions: styleOptionsDrawing //多边形的样式
        });
    };
    var setCity = function(){
        var cityCenter = function(result){
            var cityName = result.name;
            map.setCenter(cityName);
        };
        var myCity = new BMap.LocalCity();
        myCity.get(cityCenter);
    };
    var setCurrentNodes = function(treeNode){
        if(treeNode.isParent){
            $.each(treeNode.children,function(i,node){
                if(node.isParent){
                    setCurrentNodes(node);
                }else{
                    currentNodes.push(node);
                }
            });
        }else{
            currentNodes.push(treeNode);
        }
    };
    //地图画标注点方法
    var drawOverlays = function() {
        if (currentNodes.length == 1 && currentNodes[0].id == 1) {
              setCity();
            map.clearOverlays();
            return;
        }
        map.clearOverlays();
        var pointArray = new Array();
        $.each(currentNodes, function (i, node) {
            var point = new BMap.Point(node.lng, node.lat);
            var fnIcon;
            switch (node.status){
                case '1':
                    fnIcon = new BMap.Icon("img/icon/icon_open.png", new BMap.Size(14, 19), {  //开灯标志
                        offset: new BMap.Size(0, 0),
                    });
                    break;
                case '2':
                    fnIcon = new BMap.Icon("img/icon/icon_close.png", new BMap.Size(14, 19), {  //开灯标志
                        offset: new BMap.Size(0, 0),
                    });
                    break;
                case '3':
                    fnIcon = new BMap.Icon("img/icon/icon_part.png", new BMap.Size(14, 19), {  //开灯标志
                        offset: new BMap.Size(0, 0),
                    });
                    break;
                case '4':
                    fnIcon = new BMap.Icon("img/icon/icon_guzhang.png", new BMap.Size(14, 19), {  //开灯标志
                        offset: new BMap.Size(0, 0),
                    });
                    break;
                case '5':
                    fnIcon = new BMap.Icon("img/icon/icon_lixian.png", new BMap.Size(14, 19), {  //开灯标志
                        offset: new BMap.Size(0, 0),
                    });
                    break;
            }
            var marker = new BMap.Marker(point, {icon: fnIcon});        // 创建标注
            map.addOverlay(marker);
            if (i == currentNodes.length - 1) {
                //  map.panTo(point);
            }
            pointArray.push(point);
            marker.addEventListener("click", function (e) {
                currentMarker = node.id;   // 获取当前点击点的参数
                 $('#map_tap').show();
                 new Tab('map_tap');  // tab 页
                $('#timelyControl').trigger('click'); //执行实时控制方法
            });
        });
        map.setViewport(pointArray);
    };
    // 新建临时组方法
    var addGroup =function(){
        $('#add_hide').show();
    }
    /**
     * 绘图时样式
     * @type {{strokeColor: string, fillColor: string, strokeWeight: number, strokeOpacity: number, fillOpacity: number, strokeStyle: string}}
     */
    var styleOptionsDrawing = {
        strokeColor:"#FF0000",    //边线颜色。
        fillColor:"#FF0000",      //填充颜色。当参数为空时，圆形将没有填充效果。
        strokeWeight: 3,       //边线的宽度，以像素为单位。
        strokeOpacity: 0.8,    //边线透明度，取值范围0 - 1。
        fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。
        strokeStyle: 'dashed' //边线的样式，solid或dashed。
    };

    /**
     * 展示样式
     * @type {{strokeColor: string, fillColor: string, strokeWeight: number, strokeOpacity: number, fillOpacity: number, strokeStyle: string}}
     */
    var styleOptionsShow = {
        strokeColor:"#FF0000",    //边线颜色。
        fillColor:"#fff",      //填充颜色。当参数为空时，圆形将没有填充效果。
        strokeWeight: 3,       //边线的宽度，以像素为单位。
        strokeOpacity: 0.8,    //边线透明度，取值范围0 - 1。
        fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。
        strokeStyle: 'solid' //边线的样式，solid或dashed。
    };
    /**
     * 绘图完成时
     * @param e
     */
    var manualFenceInfo = new Array();
    var polygoncomplete = function(overlay){
        manualFenceInfo.length=0;
        var points = overlay.getPath();
        for(var i=0;i<points.length;i++){
            manualFenceInfo.push( new Array(points[i].lng, points[i].lat) );
        }
        //设置参数-围栏数据
        operateParam.drawData = JSON.stringify(manualFenceInfo);
        //添加区域
        addFence(operateParam,overlay);
      /*  showElecFenceVal(manualFenceInfo);*/
        operateParam={};

    };
    /**
     * 新增围栏
     */
    var addFence = function(params,overlay){
        IOT.tips('保存成功！', 'success');
        console.log(params);
        drawingManager.close(); //关闭绘画模式
        var str=['<li class="clearfix">',
                    '<span>'+addGroupName+'</span>',
                    '<button class="btn btn-red delete_group">删除</button>',
                    '<button class="btn btn-blue detail_group">详细</button>',
                    '</li>'].join('');
        $('.group_list').append(str);
        $('.detail_group').on('click',function(){  //查看详情
            map.removeOverlay(overlay);
            $('.detail_tem').show();

        })
        $('.delete_group').on('click',function(){  //删除本行
            var _this = this;
            layer.confirm('请问是否确认删除改组？', {
                btn: ['是','否']
            }, function(){
                layer.closeAll();
                $(_this).parent().remove();
                $('.detail_tem').hide();
                map.removeOverlay(overlay);
            }, function(){

            });
        })
        /*IOT.showOverlay('保存中，请稍等...');
        IOT.getServerData(URI.RENT.TRACKING.ELETIC_RANGE.ADD, params, (ret) => {
            IOT.tips(ret.msg || '操作失败，请重试！', 'error', 1000, null);
            IOT.hideOverlay();
            if (ret && ret.code === 200) {
                IOT.tips('保存成功！', 'success');
                layer.closeAll();
                titleArr.length =0;
                titleList.length =0;
                M.Table.refresh.setRange();
            } else {
                IOT.tips(ret.message || '服务器请求失败，稍后再试！', 'error');
            }
        });*/
    };
    /**
     * 显示地图中“电子围栏”
     */
    function showElecFenceVal(distributerange){
        if(jQuery.isArray(distributerange)){
            var posArray = [];
            for(var i=0; i< distributerange.length;i++){
                posArray.push(new BMap.Point(distributerange[i][0], distributerange[i][1]));
            }
            // 页面中显示的多边形
            var polygon = new BMap.Polygon(posArray,styleOptionsShow);
            map.addOverlay(polygon);
            // 将电子围栏显示在地图中间
            map.setViewport(posArray);
        }
    }
    // 加载列表方法
    var initLog =function () {
        var $accountBox = $('.run-log-table-hook');
            $accountBox.bootstrapTable('destroy');
           $accountBox.bootstrapTable('onCustomSearch');
        var $tableHook = $accountBox.bootstrapTable({
            scrollbar: 'run-log-table-body',
            striped: true, // 设置为 true 会有隔行变色效果
            pagination: true, // true 显示分页
            paginationDetail: false, // 分页详情
            sidePagination: 'server', // 服务器端
            method: 'post',
            url: URI.RUN_MONTIOR.TAB.LOG_LIST,
            debug: false,
            cache: false,
            pageNumber: 1,
            pageSize: 10,
            pageList: [10, 20, 50, 100],
            // fixedColumns: true,
            customButton: '',
            customQueryParams: function (params) {
                let formParams = '';
                let queryParams = $.extend({}, params, formParams);
                return queryParams;
            },
            onLoadSuccess: function (data) {
            },
            columns: [
                {
                    field: 'placeOrderTime', title: '时间', align: 'center', fixedLeft: true,
                    formatter: function (value, row, index) {
                        return new Date(value).Format('yyyy-MM-dd hh:mm:ss');
                    }
                },
                {
                    field: 'leaseType', title: '类型', align: 'center', fixedLeft: true,
                    formatter: function (value, row, index) {
                        /* 1短租；2长租； */
                        if (value === 1 ){return "短租";}
                        else if (value === 2 ){return "长租";}
                    }
                },
                {
                    field: 'orderStatusValue', title: '描述', align: 'center', fixedLeft: true,
                },

            ]
        });
    }
    //滑块方法
   var  scale = function (id) {
            this.oDiv=$(id);
           this.bar = this.oDiv.find('.scale');
           this.title = this.oDiv.find('.title0');
           this.step =  this.oDiv.find('.bar0');
           this.btn =  this.oDiv.find('.btn0');
        var _this=this;
       for(var i=0;i<this.oDiv.length;i++){
           (function(){
               _this.init(i);
           })(i);
       }
    };
    scale.prototype = {
        init: function (index) {
            var olength= this.title[index].innerHTML
                this.step[index].style.width = olength+ '%';
                this.btn[index].style.left =olength+ '%';
            var f = this, g = document, b = window, m = Math;
                f.btn[index].onmousedown = function (e) {
                    var x = (e || b.event).clientX;
                    var l = this.offsetLeft;
                    var max = f.bar[index].offsetWidth - this.offsetWidth;
                    g.onmousemove = function (e) {
                        var thisX = (e || b.event).clientX;
                        var to = m.min(max, m.max(-2, l + (thisX - x)));
                        f.btn[index].style.left = to + 'px';
                        f.ondrag(index,m.round(m.max(0, to / max) * 100), to);
                        b.getSelection ? b.getSelection().removeAllRanges() : g.selection.empty();
                    };
                    g.onmouseup = new Function('this.onmousemove=null');
                };
        },
        ondrag: function (index,pos, x) {
                this.step[index].style.width = Math.max(0, x) + 'px';
                this.title[index].innerHTML = pos + '';
        }
    }
    //选项卡方法
    function Tab(id){
        this.oDiv=document.getElementById(id);
        this.aHead=this.oDiv.children[0].getElementsByTagName('button');
        this.aContent=this.oDiv.children[1].getElementsByTagName('li');
        var _this=this;
        this.init();
        for(var i=0;i<this.aHead.length;i++){
            (function(index){
                _this.aHead[i].onclick=function(){
                    _this.fnClick(index);
                };
            })(i);
        }
    }
    //2.原型
    Tab.prototype.fnClick=function(index){
        for(var i=0;i<this.aHead.length;i++){
            this.aHead[i].className='';
            this.aContent[i].className='';
        }
        this.aHead[index].className='active';
        this.aContent[index].className='cur';
    };
    //初始化
    Tab.prototype.init=function(){
        for(var i=0;i<this.aHead.length;i++){
            this.aHead[i].className='';
            this.aContent[i].className='';
        }
        this.aHead[0].className='active';
        this.aContent[0].className='cur';
    };

})();
